/* pages/customerInfo/customerInfo.ts */
interface CustomerInfo {
    name: string;
    phone: string;
    email?: string;
    address?: string;
  }
  
  Page({
    data: {
      name: '',
      phone: '',
      email: '',
      address: '',
      nameExists: false // 用于标识名字是否已存在
    },
  
    onLoad() {
      const eventChannel = this.getOpenerEventChannel();
      eventChannel.on('editCustomer', (user: CustomerInfo) => {
        this.setData({
          name: user.name,
          phone: user.phone,
          email: user.email || '',
          address: user.address || ''
        });
      });
    },
  
    // 更新输入值
    onInputChange(e: WechatMiniprogram.Input) {
      const { field } = e.target.dataset as { field: string };
      const value = e.detail.value;
      this.setData({
        [field]: value
      });
  
      // 检查名字是否已存在
      if (field === 'name') {
        const users: CustomerInfo[] = wx.getStorageSync('users') || [];
        const nameExists = users.some(user => user.name === value);
        this.setData({
          nameExists
        });
      }
    },
  
    // 保存用户信息
    onSave() {
      const { name, phone, email, address, nameExists } = this.data;
      if (nameExists) {
        wx.showToast({
          title: '该名字已存在，请使用其他名字',
          icon: 'none'
        });
        return;
      }
  
      if (name && phone) { // 仅检查必填字段
        const userInfo: CustomerInfo = {
          name,
          phone,
          email: email || '', // 如果未填写电子邮箱，默认为空字符串
          address: address || '' // 如果未填写地址，默认为空字符串
        };
        const users = wx.getStorageSync('users') || [];
        const index = users.findIndex((user: { name: string; phone: string; }) => user.name === name && user.phone === phone);
        if (index > -1) {
          users[index] = userInfo; // 更新用户信息
        } else {
          users.push(userInfo); // 添加新用户
        }
        wx.setStorageSync('users', users);
        wx.showToast({
          title: '用户信息保存成功',
          icon: 'success',
          duration: 2000,
          complete: () => {
            wx.navigateBack(); // 保存成功后返回上一页
          }
        });
      } else {
        wx.showToast({
          title: '请填写必填字段',
          icon: 'none'
        });
      }
    }
  });
  